package com.huluobo.apps.pages

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.apps.AppsIntent
import com.huluobo.apps.AppsViewModel
import com.huluobo.apps.entity.AppsEntity
import com.huluobo.apps.entity.AppsEntityItem
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 *  Created by LC on 2025/5/26.
 *  hiltViewModel compose中可以直接通过hilt来拿到对应的viewModel,不需要使用其他方式获取
 */

@Composable
fun AppsPage(navHostController: NavHostController, vm: AppsViewModel = hiltViewModel()) {
    val list = remember {
        //快照的list,当list发生改变时,会刷新页面直接展示新的数据
        SnapshotStateList<AppsEntityItem>()
    }

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    //弹出安装进度条
    var launch by remember {
        mutableStateOf(false)
    }

    //安装的进度
    var currentProgress by remember {
        mutableStateOf(0f)
    }

    //控制更新进度的协程
    var scope = rememberCoroutineScope()

    //开启协程,获取成功或者失败的状态 key1 触发网络请求的key 传递null的字符串就代表当前页面创建时就会创建该协程
    LaunchedEffect(key1 = "", block = {
        launch {
            //开启新的协程,接收vm中所有的状态
            vm.state.collect {
                when (it) {
                    is UIState.OnError -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取应用程序列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }

                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
                        //* 代表获取所有的状态,只要是一个Succes的状态就会在当前括号中获取到
                        if (it.type == StateType.DEFAULT) {
                            list.clear()
                            //由于在请求时Entity会转化为Any的形式,这里需要强转回来
                            list.addAll(it.data as AppsEntity)
                        }

                        if (it.type == StateType.DOWNLOAD) {
                            ToastUtils.showLong(it.data.toString())
                        }
                    }
                }
            }
        }

        //默认创建的位置,发起意图
        vm.sendIntent(AppsIntent.GetApps)
    })

    if (isShowProgress) {
        BaseLoadingDialog()
    }

    Column(Modifier.padding(10.dp)) {
        BaseTitle(title = "在线应用", navHostController = navHostController)
        Spacer(modifier = Modifier.height(10.dp))
        LazyVerticalGrid(columns = GridCells.Fixed(3), content = {
            items(list) {
                AppsItem(appsEntityItem = it, vm) {
                    //弹出横向进度条
                    launch = true
                    //通过协程来模拟10秒
                    scope.launch {
                        for (i in 1..100) {
                            currentProgress = i.toFloat() / 100
                            //延迟0.1秒更新一次进度
                            delay(100)
                        }
                        //关闭进度条
                        launch = false
                        ToastUtils.showLong("安装成功")
                    }
                }
            }
        }, verticalArrangement = Arrangement.spacedBy(20.dp))
        if (launch) {
            //横向的进度条
            LinearProgressIndicator(
                progress = currentProgress,
                Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 40.dp)
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AppsItem(appsEntityItem: AppsEntityItem, vm: AppsViewModel, longClick: () -> Unit) {
    //通过app的context,拿到当前app下的下载文件夹,如果没有会自动创建一个
    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    //系统文件夹
//    val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

    //控制下载的弹窗
    var isShow by remember {
        mutableStateOf(false)
    }
    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.combinedClickable(
        onClick = {
            isShow = true
        },
        onLongClick = {
            longClick()
        }
    )) {
        AsyncImage(model = appsEntityItem.appIcon, contentDescription = "", modifier = Modifier.size(40.dp))
        Spacer(modifier = Modifier.height(10.dp))
        Text(text = appsEntityItem.appName)
    }

    if (isShow) {
        AlertDialog(onDismissRequest = { isShow = false }, confirmButton = {
            TextButton(onClick = {
                vm.sendIntent(
                    AppsIntent.DownloadApk(
                        appsEntityItem.apkUrl,
                        File(file, appsEntityItem.appName + ".apk")
                    )
                )
                isShow = false
            }) {
                Text(text = "确认")
            }
        }, dismissButton = {
            TextButton(onClick = {
                isShow = false
            }) {
                Text(text = "取消")
            }
        }, title = {
            Text(text = "下载提醒")
        }, text = {
            Text(text = "是否要下载${appsEntityItem.appName}吗?")
        })
    }
}